package com.wjy.sfhcore.ui.fragment.list;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;

import com.wjy.sfhcore.ui.fragment.LoadFragment;
import com.wjy.sfhcore.ui.third_party.listviewanimations.swinginadapters.AnimationAdapter;
import com.wjy.sfhcore.ui.third_party.listviewanimations.swinginadapters.prepared.AlphaInAnimationAdapter;
import com.wjy.sfhcore.ui.third_party.refresh.base.PullToRefreshAdapterViewBase;
import com.wjy.sfhcore.ui.third_party.refresh.base.PullToRefreshBase;
import com.wjy.sfhcore.util.ConstantUtil;
import com.wjy.sfhcore.util.Tools;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * AdapterView上拉刷新，下拉加载更多基类
 *
 * @param <D> 数据对象
 * @param <L> Loader对象
 * @param <T> AdapterView对象
 * @author wjy
 */
public abstract class BaseAdapterViewFragment<D, L, T extends AbsListView>
        extends LoadFragment<L> implements PullToRefreshBase.OnLastItemVisibleListener,
        PullToRefreshBase.OnRefreshListener2<T>, OnItemClickListener, OnItemLongClickListener {
    protected int mTotalPages = 0;// 总页数
    protected int mPageIndex = 0;// 当前页数
    protected boolean isRefresh = false;
    protected T mAdapterView;
    protected PullToRefreshAdapterViewBase<T> mAdapterViewBase;
    protected BaseListAdapter<D> mAdapter;
    protected List<D> mItems;
    protected String lastRefreshDate;
    protected AnimationAdapter animationAdapter;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListViews(view);
    }

    public void initListViews(View view) {
        initAdapterView(view);
        mAdapterViewBase.setOnRefreshListener(this);
        mAdapterViewBase.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mAdapterViewBase.setOnLastItemVisibleListener(this);
        if (mAdapter == null) {
            mItems = new ArrayList<>();
            mAdapter = getAdapter();
            animationAdapter = initAdapterAnimation(mAdapter);
        }
        animationAdapter.setAbsListView(mAdapterView);
        animationAdapter
                .setInitialDelayMillis(ConstantUtil.LIST_ANIMATION_TIME);
        setAdapter();
    }

    /**
     * 初始化adapter item view动画效果 默认为淡入动画.
     *
     * @param mAdapter
     * @return
     */
    protected AnimationAdapter initAdapterAnimation(BaseAdapter mAdapter) {
        return new AlphaInAnimationAdapter(mAdapter);
    }

    protected abstract void setAdapter();

    protected abstract void initAdapterView(View view);

    protected abstract BaseListAdapter<D> getAdapter();

    /**
     * 刷新的时候调用，需要传入页数等 上拉，下拉均调用此方法去获取数据
     */
    protected abstract void getDatas();

    protected T getListView() {
        return mAdapterView;
    }

    protected View initHeaderChildView() {
        return null;
    }


    protected void setListShown(boolean isListShown) {
        if (isListShown) {
            mAdapterView.setVisibility(View.VISIBLE);
        }
    }

    protected void dataLoadFinish() {
        // hide loading progress bar
        setListShown(true);
        onLoad();
    }

    /**
     * @param totalPage
     */
    protected void setTotalPages(int totalPage) {
        mTotalPages = totalPage;
    }

    /**
     * 得到总页数
     *
     * @param totalNum 总数量
     * @return
     */
    protected int getTotalPages(int totalNum) {
        return totalNum % ConstantUtil.PAGE_SIZE == 0 ? (totalNum / ConstantUtil.PAGE_SIZE)
                : (totalNum / ConstantUtil.PAGE_SIZE + 1);
    }

    protected int getPageIndex() {
        return mPageIndex;
    }

    /**
     * 列表下拉刷新调用的方法
     */
    public void onRefresh() {
        setListShown(false);
        mPageIndex = 0;
        mAdapterView.setSelection(0);
        mAdapterViewBase.setRefreshing();
        if (!isRefresh) {
            isRefresh = true;
            getDatas();
        }
    }

    /**
     * 列表上拉载入更多
     */
    public void onLoadMore() {
        mPageIndex++;
        if (mPageIndex >= mTotalPages)
            return;
        getDatas();
    }

    protected void setDatas(List<D> items) {
        if (isRefresh) {
            mItems.clear();
            isRefresh = false;
        }

        if (items == null) {
            dataLoadFinish();
            return;
        }

        for (D item : items) {
            mItems.add(item);
        }

        mAdapter.setDatas(mItems);
        dataLoadFinish();
    }

    protected List<D> getItems() {
        return mItems;
    }

    /**
     * 数据加载完成之后调用
     */
    protected void onLoad() {
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
        lastRefreshDate = sformat.format(new Date());
        mAdapterViewBase.onRefreshComplete();
        // mAdapterViewBase.getLoadingLayoutProxy().setLastUpdatedLabel(
        // Tools.isEmpty(lastRefreshDate) ? ""
        // : getString(R.string.xlistview_header_last_time)
        // + Tools.trim(lastRefreshDate));
        // ll_footer.setVisibility(View.GONE);
        if (mPageIndex == mTotalPages - 1 || mTotalPages <= 1) {
            setLoadingMore(false);
        } else {
            setLoadingMore(true);
        }
    }

    protected void setLoadingMore(boolean isHasMore) {
        if (isHasMore) {
            mAdapterViewBase.setAutoLoadingVisable(true);
        } else {
            mAdapterViewBase.setAutoLoadingVisable(false);
        }
    }

    public void onLastItemVisible() {
        if (mPageIndex == mTotalPages - 1 || mTotalPages <= 1) {
            return;
        }
        onLoadMore();
    }


    public void onPullDownToRefresh(PullToRefreshBase<T> refreshView) {
        onRefresh();
    }

    public void onPullUpToRefresh(PullToRefreshBase<T> refreshView) {
        onLoadMore();
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        if (arg2 < 1) {
            return;
        }
        onRealItemClick(arg0, arg1, arg2 - 1, arg3);
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   int position, long id) {
        if (position < 1) {
            return false;
        }
        onRealItemLongClick(parent, view, position - 1, id);
        return true;
    }

    /**
     * 子类重写此方法
     *
     * @param arg0
     * @param arg1
     * @param realPosition
     * @param arg3
     */
    protected void onRealItemClick(AdapterView<?> arg0, View arg1,
                                   int realPosition, long arg3) {
    }

    /**
     * 子类重写此方法
     *
     * @param arg0
     * @param arg1
     * @param realPosition
     * @param arg3
     */
    protected void onRealItemLongClick(AdapterView<?> arg0, View arg1,
                                       int realPosition, long arg3) {
    }

    /**
     * 发起数据加载
     */
    public void loadData() {
        if (Tools.isConnectNet(baseActivity)) {
            changeViewState(LoadResult.LOADING);
            getDatas();
        } else {
            changeViewState(LoadResult.NO_NET);
        }
    }
}
